package com.scalar.chiptrack.adaptor.jsi;

import com.scalar.chiptrack.jobs.JobHandler;
import com.scalar.chiptrack.adaptor.AdaptorConstants;
import com.scalar.chiptrack.adaptor.InventoryLot;
import com.scalar.chiptrack.adaptor.AdaptorUtils;
import com.scalar.chiptrack.adaptor.ShippedLot;
import com.scalar.chiptrack.adaptor.dao.InventoryLotDAO;
import com.scalar.chiptrack.adaptor.dao.AdaptorDAO;
import com.scalar.chiptrack.adaptor.dao.ShippedLotDAO;
import com.scalar.chiptrack.adaptor.dao.AdaptorRunInfo;
import com.scalar.chiptrack.utils.Logger;
import com.scalar.chiptrack.utils.StringUtils;
import com.scalar.ScalarException;

import java.io.File;

import java.util.HashMap;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import java.util.Locale;

import jxl.Workbook;
import jxl.Sheet;
import jxl.Cell;
import jxl.CellType;
import jxl.DateCell;


/**
 * Created by IntelliJ IDEA.
 * User: Sudhakar
 * Date: Mar 21, 2007
 * Time: 12:28:26 PM
 */
public class JSIFGDataParser extends JobHandler implements AdaptorConstants
{
    HashMap m_fgDataMap     = new HashMap();
    HashMap m_shipDataMap   = new HashMap();

    private Logger m_parserLogger       = null;
    private String m_dataOutputDir      = null;

    /**
     *
     * @throws ScalarException
     */
    public JSIFGDataParser() throws ScalarException
    {
        try
        {
            m_dataOutputDir = AdaptorUtils.getDataOutputDir(VENDOR_NAME_JSI, INVENTORY_TYPE_FINISHED_GOODS);
            AdaptorUtils.makeAllAdaptorDirs( m_dataOutputDir );
            m_parserLogger =  AdaptorUtils.getDataParserLogger( m_dataOutputDir,VENDOR_NAME_JSI );
            // All the DAOs and Parser should be logging into same file
            ShippedLotDAO.setLogger(m_parserLogger);
            InventoryLotDAO.setLogger(m_parserLogger);
            AdaptorUtils.setLogger( m_parserLogger );
        }
        catch (ScalarException se)
        {
            log("ERROR!! ERROR!! ERROR!! Exception while loading JSI output directory details from database, Exception: " + se);
            throw se;
        }
    }
    /**
     *
     * @param args
     * @throws Exception
     */
    public static void main(String args[]) throws Exception
    {
        new JSIFGDataParser().execute();
    }
    /**
     *
     * @throws Exception
     */
    public void execute() throws Exception
    {
        AdaptorUtils.printHeader(VENDOR_NAME_JSI, CONSTANT_PARSER );

        File doneDestDir = new File(m_dataOutputDir + "/done");

        File wipDataoutDir = new File(m_dataOutputDir);


        File[] fileList = wipDataoutDir.listFiles();

        if ((fileList == null) || (fileList.length <= 3))
        {
           log("No file found in directory: " + wipDataoutDir);
           throw new ScalarException("No file found in directory: " + wipDataoutDir + "----\n\n");
        }

        ArrayList successFileList   = new ArrayList();
        ArrayList jsiWipList        = null;
        ArrayList jsiShipList       = null;
        boolean success             = true;

        for (int i = 0; i < fileList.length; i++)
        {
            if (fileList[i].isDirectory() == true)
            {
                continue;
            }

            if (fileList[i].getName() != null && fileList[i].getName().trim().startsWith(JSIFtpAdaptor.FILE_NAME_JSI_WIP))
            {
                jsiWipList = parseJsiWipsheet(fileList[i].getAbsolutePath());

                if (jsiWipList != null && jsiWipList.size() > 0) {
                    getJsiWipDetails(jsiWipList);
                }

                //Add files to success list to move to /done directory
                successFileList.add(fileList[i]);
            }
            if (fileList[i].getName() != null && ( fileList[i].getName().trim().indexOf(JSIFtpAdaptor.FILE_NAME_JSI_SHIP) != -1 ))
            {
                // Parse the file and get the lot list

                jsiShipList = parseJsiShipsheet(fileList[i].getAbsolutePath());
                if (jsiShipList != null && jsiShipList.size() > 0) {
                    getJsiShipDetails(jsiShipList);
                }

                //Add files to success list to move to /done directory
                successFileList.add(fileList[i]);
            }
        }
        /*Updating the FG Lot Information*/
        try
        {
            // Save Finished Goods Information
            if (m_fgDataMap.isEmpty() == false)
            {
                log(" Updating Finished Goods Lot Information");
                InventoryLotDAO.saveInventoryLot(null, m_fgDataMap.values().iterator(), LOCATION_TYPE_FG, VENDOR_NAME_JSI);
            }
            else
            {
                InventoryLotDAO.closeInventoryLot(null, LOCATION_TYPE_FG, VENDOR_NAME_JSI);
            }
        }
        catch (ScalarException se)
        {
            success = false;
            se.printStackTrace();
            log("ERROR!! ERROR!! ERROR!! Could not update Finished Goods Lot information into database: " + se);
            throw se;
        }
        // Save Finished Goods shipping info
        try
        {
            if (m_shipDataMap.isEmpty() == false)
            {
                log("Updating shipment Information");
                ShippedLotDAO.saveShippedLot( null, m_shipDataMap.values().iterator());
            }
        }
        catch (Exception e)
        {
            success = false;
            log("ERROR!! ERROR!! ERROR!! Could not update JSI Finished Goods Shipping information into database: " + e);
            e.printStackTrace();
            throw e;
        }

        // TO SEND THE NEW LOTS, NEW TRANSIT LOTS, NO PO LOTS, DISCREPANCY LOTS NOTIFICATIONS TO THE USER
        AdaptorDAO.sendAllNotifications(VENDOR_NAME_JSI, true, true, true);

        // To Close the Drop Out Lots
        AdaptorDAO.closeDropOutLots(VENDOR_NAME_JSI);

        int adaptor_id = AdaptorRunInfo.getLastRunAdaptorId( JSIFtpAdaptor.ADAPTOR_NAME, CONSTANT_ADAPTOR);
        
        // Update Adaptor_Run_Info table
        try
        {
            if ( success == true )
            {
                AdaptorRunInfo.saveAdaptorLastUpdatedStatus(CONSTANT_PARSER, JSIFtpAdaptor.ADAPTOR_NAME, CONSTANT_SUCCESS, adaptor_id);
                System.out.println( "SUCCESSFULLY UPDATED IN THE DATABASE" );
            }
        }
        catch ( ScalarException se )
        {
            success = false; //As filES DATA SAVED , UPDATEING AS SUCCESS
            AdaptorRunInfo.saveAdaptorLastUpdatedStatus(CONSTANT_PARSER, JSIFtpAdaptor.ADAPTOR_NAME, CONSTANT_SUCCESS, adaptor_id);
            log( "WARNING!! WARNING!! WARNING!! Could not update Adaptor run information, Exception: " + se );
            throw se;
        }
        // Move the successful files to 'done' directory
       if ( success )
       {
           AdaptorUtils.moveFilesToDone( successFileList, doneDestDir );
       }
    }
    /**
     *
     * @param fileName
     * @return
     * @throws Exception
     */
    private ArrayList parseJsiWipsheet( String fileName ) throws Exception
    {
        ArrayList jsiFgList     = new ArrayList();
        JSIFGStatus jsifgStatus = null;
        String checkValue;

        if (fileName == null)
        {
            throw new ScalarException("Filename argument is null");
        }

        try
        {
            File wipStatusFile = new File(fileName);

            if (wipStatusFile.exists() == false)
            {
                throw new ScalarException(fileName + " doesnt exist");
            }

            log("\nFound " + fileName);
            log("Parsing the file for JSI FG Report...");
            System.out.println("\nFound " + fileName);
            System.out.println("Parsing the file for JSI FG Report...");

            Workbook workbook = Workbook.getWorkbook(wipStatusFile);
            Sheet sheet = workbook.getSheet(0);

            Cell[] row = null;

            for ( int rowCount = 1; rowCount < sheet.getRows(); rowCount++ )
            {
                row = sheet.getRow( rowCount );

                jsifgStatus = new JSIFGStatus();

                checkValue = row[1].getContents().trim();

                if( checkValue != null && checkValue.trim().length() > 0 )
                {
                    if (row.length > 0)
                    {
                        if (row[0].getType().equals(CellType.EMPTY))
                        {
                            jsifgStatus.setStockCode(null);
                        }
                        else
                        {
                            jsifgStatus.setStockCode(row[0].getContents().trim());
                        }
                    }
                    if (row.length > 1)
                    {
                        if (row[1].getType().equals(CellType.EMPTY))
                        {
                            jsifgStatus.setPartNumber(null);
                        }
                        else
                        {
                            jsifgStatus.setPartNumber(row[1].getContents().trim());
                        }
                    }
                    if (row.length > 2)
                    {
                        if (row[2].getType().equals(CellType.EMPTY))
                        {
                            jsifgStatus.setCountryofOrigin(null);
                        }
                        else
                        {
                            jsifgStatus.setCountryofOrigin(row[2].getContents().trim());
                        }
                    }
                    if (row.length > 3)
                    {
                        if (row[3].getType().equals(CellType.EMPTY))
                        {
                            jsifgStatus.setContainerID(null);
                        }
                        else
                        {
                            jsifgStatus.setContainerID(row[3].getContents().trim());
                        }
                    }
                    if (row.length > 4)
                    {
                        if (row[4].getType().equals(CellType.EMPTY))
                        {
                            jsifgStatus.setDateofReciept(null);
                        }
                        else if( row[4].getType().equals( CellType.DATE ))
                        {
                            DateCell dc = (DateCell) row[4];
                            java.util.Date dateofReceipt = null;
                            dateofReceipt = dc.getDate();

                            if ("America/Los_Angeles".equals(System.getProperty("user.timezone")))
                            {
                                Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"), Locale.US);
                                cal.setTime(dateofReceipt);
                                dateofReceipt = new GregorianCalendar(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DATE)).getTime();
                                jsifgStatus.setDateofReciept(StringUtils.formatDateToString(dateofReceipt));
                            }
                            else
                            {
                                Calendar cal = new GregorianCalendar();
                                cal.setTime(dateofReceipt);
                                dateofReceipt = new GregorianCalendar(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DATE)).getTime();
                                jsifgStatus.setDateofReciept(StringUtils.formatDateToString(dateofReceipt));
                            }
                        }
                    }
                    if (row.length > 5)
                    {
                        if (row[5].getType().equals(CellType.EMPTY))
                        {
                            jsifgStatus.setLotNumber(null);
                        }
                        else
                        {
                            jsifgStatus.setLotNumber(row[5].getContents().trim());
                        }
                    }
                    if (row.length > 6)
                    {
                        if (row[6].getType().equals(CellType.EMPTY))
                        {
                            jsifgStatus.setDateCode(null);
                        }
                        else
                        {
                            jsifgStatus.setDateCode(row[6].getContents().trim());
                        }
                    }
                    if (row.length > 7)
                    {
                        if (row[7].getType().equals(CellType.EMPTY))
                        {
                            jsifgStatus.setLocation(null);
                        }
                        else
                        {
                            jsifgStatus.setLocation(row[7].getContents().trim());
                        }
                    }
                    if (row.length > 8)
                    {
                        if (row[8].getType().equals(CellType.EMPTY))
                        {
                            jsifgStatus.setUom(null);
                        }
                        else
                        {
                            jsifgStatus.setUom(row[8].getContents().trim());
                        }
                    }
                    if (row.length > 9)
                    {
                        if (row[9].getType().equals(CellType.EMPTY))
                        {
                            jsifgStatus.setQtyAailable(null);
                        }
                        else
                        {
                            if (row[9].getContents() != null && row[9].getContents().trim().length() > 0 )
							{
								jsifgStatus.setQtyAailable(row[9].getContents().trim().replaceAll(",", ""));
							}
                        }
                    }
                    if (row.length > 10)
                    {
                        if (row[10].getType().equals(CellType.EMPTY))
                        {
                            jsifgStatus.setQtyAllocated(null);
                        }
                        else
                        {
                            jsifgStatus.setQtyAllocated(row[10].getContents().trim());
                        }
                    }
                    if (row.length > 11)
                    {
                        if (row[11].getType().equals(CellType.EMPTY))
                        {
                            jsifgStatus.setQtyReserved(null);
                        }
                        else
                        {
                            jsifgStatus.setQtyReserved(row[11].getContents().trim());
                        }
                    }

                    jsiFgList.add( jsifgStatus );
                }
            }
        }
        catch ( Exception e )
        {
            throw new ScalarException( "Exception " + e );
        }

        return jsiFgList;
    }
    /**
     *
     * @param fileName
     * @return
     * @throws Exception
     */
    private ArrayList parseJsiShipsheet(String fileName) throws Exception
    {
        ArrayList jsiShipList       = new ArrayList();
        JSIShipStatus jsiShipStatus = null;
        String partNumber           = null;
        String shippedDate          = null;
        JSIShipStatus shipStatus    = null;
        String billedTo             = null;
        String shippedTo            = null;
        String checkValue;

        if (fileName == null)
        {
            throw new ScalarException("Filename argument is null");
        }

        try
        {
            File shipStatusFile = new File(fileName);

            if (shipStatusFile.exists() == false)
            {
                throw new ScalarException(fileName + " doesnt exist");
            }

            log("\nFound " + fileName);
            log("Parsing the file for JSI Ship Report...");
            System.out.println("\nFound " + fileName);
            System.out.println("Parsing the file for JSI Ship Report...");

            Workbook workbook = Workbook.getWorkbook(shipStatusFile);
            Sheet sheet = workbook.getSheet("Shipping Report");

            Cell[] row = null;

            for (int rowCount = 2; rowCount < sheet.getRows(); rowCount++)
            {
                row = sheet.getRow(rowCount);
                jsiShipStatus = new JSIShipStatus();

                if (row != null && row.length > 10)
                {
                    checkValue = row[9].getContents().trim();

                    if (checkValue != null && checkValue.trim().length() > 0 && !checkValue.startsWith("TOTAL"))
                    {
                        if (row.length > 0)
                        {
                            if (row[0].getType().equals(CellType.EMPTY))
                            {
                                jsiShipStatus.setShipDate(null);
                            }
                            else if( row[0].getType().equals( CellType.DATE ))
                            {
                                DateCell dc = (DateCell) row[0];
                                java.util.Date shipDate = null;
                                shipDate = dc.getDate();

                                if ("America/Los_Angeles".equals(System.getProperty("user.timezone")))
                                {
                                    Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"), Locale.US);
                                    cal.setTime(shipDate);
                                    shipDate = new GregorianCalendar(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DATE)).getTime();
                                    jsiShipStatus.setShipDate(StringUtils.formatDateToString(shipDate));
                                }
                                else
                                {
                                    Calendar cal = new GregorianCalendar();
                                    cal.setTime(shipDate);
                                    shipDate = new GregorianCalendar(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DATE)).getTime();
                                    jsiShipStatus.setShipDate(StringUtils.formatDateToString(shipDate));
                                }
                            }
                        }
                        if (row.length > 1)
                        {
                            if (row[1].getType().equals(CellType.EMPTY))
                            {
                                jsiShipStatus.setJobNumber(null);
                            }
                            else
                            {
                                jsiShipStatus.setJobNumber(row[1].getContents().trim());
                            }
                        }
                        if (row.length > 2)
                        {
                            if (row[2].getType().equals(CellType.EMPTY))
                            {
                                jsiShipStatus.setPoNumber(null);
                            }
                            else
                            {
                                jsiShipStatus.setPoNumber(row[2].getContents().trim());
                            }
                        }
                        if (row.length > 3)
                        {
                            if (row[3].getType().equals(CellType.EMPTY))
                            {
                                jsiShipStatus.setSalesOrderNo(null);
                            }
                            else
                            {
                                jsiShipStatus.setSalesOrderNo(row[3].getContents().trim());
                            }
                        }
                        if (row.length > 4)
                        {
                            if (row[4].getType().equals(CellType.EMPTY))
                            {
                                jsiShipStatus.setDn(null);
                            }
                            else
                            {
                                jsiShipStatus.setDn(row[4].getContents().trim());
                            }
                        }
                        if (row.length > 5)
                        {
                            if (row[5].getType().equals(CellType.EMPTY))
                            {
                                jsiShipStatus.setShipTo(null);
                            }
                            else
                            {
                                jsiShipStatus.setShipTo(row[5].getContents().trim());
                            }
                        }
                        if (row.length > 6)
                        {
                            if (row[6].getType().equals(CellType.EMPTY))
                            {
                                jsiShipStatus.setBilledTo(null);
                            }
                            else
                            {
                                jsiShipStatus.setBilledTo(row[6].getContents().trim());
                            }
                        }
                        if (row.length > 7)
                        {
                            if (row[7].getType().equals(CellType.EMPTY))
                            {
                                jsiShipStatus.setPartNumber(null);
                            }
                            else
                            {
                                jsiShipStatus.setPartNumber(row[7].getContents().trim());
                            }
                        }
                        if (row.length > 8)
                        {
                            if (row[8].getType().equals(CellType.EMPTY))
                            {
                                jsiShipStatus.setPartIn(null);
                            }
                            else
                            {
                                jsiShipStatus.setPartIn(row[8].getContents().trim());
                            }
                        }
                        if (row.length > 9)
                        {
                            if (row[9].getType().equals(CellType.EMPTY))
                            {
                                jsiShipStatus.setLotNumber(null);
                            }
                            else
                            {
                                jsiShipStatus.setLotNumber(row[9].getContents().trim());
                            }
                        }
                        if (row.length > 10)
                        {
                            if (row[10].getType().equals(CellType.EMPTY)) {
                                jsiShipStatus.setShipQty(null);
                            }
                            else
                            {
                                jsiShipStatus.setShipQty(row[10].getContents().trim());
                            }
                        }
                        if (row.length > 11)
                        {
                            if (row[11].getType().equals(CellType.EMPTY))
                            {
                                jsiShipStatus.setOuterBoxes(null);
                            }
                            else
                            {
                                jsiShipStatus.setOuterBoxes(row[11].getContents().trim());
                            }
                        }
                        if (row.length > 12)
                        {
                            if (row[12].getType().equals(CellType.EMPTY))
                            {
                                jsiShipStatus.setForwardingAgent(null);
                            }
                            else
                            {
                                jsiShipStatus.setForwardingAgent(row[12].getContents().trim());
                            }
                        }
                        if (row.length > 13)
                        {
                            if (row[13].getType().equals(CellType.EMPTY))
                            {
                                jsiShipStatus.setMawb(null);
                            }
                            else
                            {
                                jsiShipStatus.setMawb(row[13].getContents().trim());
                            }
                        }
                        if (row.length > 14)
                        {
                            if (row[14].getType().equals(CellType.EMPTY))
                            {
                                jsiShipStatus.setHawb(null);
                            }
                            else
                            {
                                jsiShipStatus.setHawb(row[14].getContents().trim());
                            }
                        }
                        if (row.length > 15)
                        {
                            if (row[15].getType().equals(CellType.EMPTY))
                            {
                                jsiShipStatus.setFlight(null);
                            }
                            else
                            {
                                jsiShipStatus.setFlight(row[15].getContents().trim());
                            }
                        }
                        /* Sets previous rows shipdate and  partNumber values*/
                        if (jsiShipStatus.getPartNumber() == null && jsiShipStatus.getShipDate() == null)
                        {
                            for (int i = jsiShipList.size() - 1; i >= 0; i--)
                            {
                                shipStatus = (JSIShipStatus) jsiShipList.get(i);

                                if (shipStatus.getPartNumber() != null && shipStatus.getShipDate() != null)
                                {
                                    shippedDate = shipStatus.getShipDate();
                                    partNumber = shipStatus.getPartNumber();
                                    billedTo = shipStatus.getBilledTo();
                                    shippedTo = shipStatus.getShipTo();
                                    break;
                                }
                            }
                            if (shippedDate != null)
                            {
                                jsiShipStatus.setShipDate(shippedDate);
                            }
                            if (partNumber != null)
                            {
                                jsiShipStatus.setPartNumber(partNumber);
                            }
                            if (billedTo != null)
                            {
                                jsiShipStatus.setBilledTo(billedTo);
                            }
                            if (shippedTo != null)
                            {
                                jsiShipStatus.setShipTo(shippedTo);
                            }
                        }

                        jsiShipList.add(jsiShipStatus);
                    }
                }
            }
        }
        catch (Exception e)
        {
            throw new ScalarException("Exception " + e);
        }

        return jsiShipList;
    }

    /**
     *
     * @param jsiFgList
     */
    public void getJsiWipDetails(ArrayList jsiFgList)
    {
        String partNumber               = null;
        String lotNumber                = null;
        JSIFGStatus jsiFgStatus         = null;
        InventoryLot inventoryLot       = null;

        try
        {
            Iterator jsiFgIterator = jsiFgList.iterator();

            while (jsiFgIterator.hasNext())
            {
                jsiFgStatus = (JSIFGStatus) jsiFgIterator.next();

                partNumber = jsiFgStatus.getPartNumber();
                lotNumber = jsiFgStatus.getVendorLotNumber();

                if( partNumber != null && lotNumber != null )
                {
                    inventoryLot = (InventoryLot) m_fgDataMap.get(lotNumber + partNumber);
                    if (inventoryLot == null)
                    {
                        inventoryLot = new InventoryLot(VENDOR_NAME_JSI, LOCATION_TYPE_FG );
                        m_fgDataMap.put(lotNumber + partNumber, inventoryLot);
                    }

                    int quantity = 0;
                    if (inventoryLot.getQtyIn() != null)
                    {
                        try
                        {
                            quantity = Integer.parseInt(inventoryLot.getQtyIn());
                        }
                        catch (NumberFormatException npe)
                        {
                        }
                        try
                        {
                            quantity += Integer.parseInt(jsiFgStatus.getQtyAailable() );
                        }
                        catch (NumberFormatException npe)
                        {
                        }
                    }
                    else
                    {
                        try
                        {
                            quantity = Integer.parseInt(jsiFgStatus.getQtyAailable());
                        }
                        catch (NumberFormatException npe)
                        {
                        }
                    }

                    String dateIn           = null;
                    String dateofReciept    = null;

                    if( inventoryLot.getDateIn() != null )
                    {
                        dateIn = inventoryLot.getDateIn() ;
                    }
                    if ( jsiFgStatus.getDateofReciept() != null && jsiFgStatus.getDateofReciept().trim().length() > 0 )
                    {
                        dateofReciept = jsiFgStatus.getDateofReciept();
                    }
                    if( ( dateofReciept != null ) && ( dateIn != null ) )
                    {
                        java.util.Date tempDate1 = StringUtils.getSQLDate( dateofReciept, "MM/dd/yyyy");
                        java.util.Date tempDate2 = StringUtils.getSQLDate( dateIn,"MM/dd/yyyy");
                        if ( tempDate1 != null && tempDate2 != null )
                        {
                            if ( tempDate1.compareTo( tempDate2 ) > 0 )
                            {
                                dateofReciept = dateIn;
                            }
                        }
                    }

                    if (quantity > 0)
                    {
                        inventoryLot.setLotNumber(lotNumber);
                        inventoryLot.setPartNumber(partNumber);
                        inventoryLot.setDateIn(dateofReciept);
                        inventoryLot.setDateCode( jsiFgStatus.getDateCode() );
                        inventoryLot.setQtyIn(quantity + "");
                        inventoryLot.setStatus(LOT_STATUS_RUNNING);
                        inventoryLot.setFabLotNumber( jsiFgStatus.getLotNumber());
                    }
                }
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
            log("ERROR!ERROR! While parsing the JSI FG Details" + e);
            System.out.println("ERROR!ERROR! While parsing the JSI FG Details" + e);
        }
    }

    /**
     *
     * @param jsiShipList
     */
    public void getJsiShipDetails(ArrayList jsiShipList)
    {

        String partNumber           = null;
        String lotNumber            = null;
        JSIShipStatus jsiShipStatus = null;
        ShippedLot shippedLot       = null;

        try
        {
            Iterator jsiFgIterator = jsiShipList.iterator();

            while (jsiFgIterator.hasNext())
            {
                jsiShipStatus = (JSIShipStatus) jsiFgIterator.next();

                partNumber = jsiShipStatus.getPartNumber();
                lotNumber  = jsiShipStatus.getLotNumber();

                if (partNumber != null && lotNumber != null)
                {
                    shippedLot = (ShippedLot) m_shipDataMap.get(partNumber + lotNumber);

                    if (shippedLot == null)
                    {
                        shippedLot = new ShippedLot();
                        m_shipDataMap.put(partNumber + lotNumber, shippedLot);
                    }
                    int shipQty = 0;
                    if (shippedLot.getShipQty() != null)
                    {
                        try
                        {
                            shipQty = Integer.parseInt(shippedLot.getShipQty());
                        }
                        catch (NumberFormatException ignore) {
                        }
                        try
                        {
                            shipQty += Integer.parseInt(jsiShipStatus.getShipQty());
                        }
                        catch (NumberFormatException ignore) {
                        }
                    }
                    else
                    {
                        try
                        {
                            shipQty = Integer.parseInt(jsiShipStatus.getShipQty());
                        }
                        catch (NumberFormatException ignore) {
                        }
                    }

                    String shipDate = null;
                    String shippedDate = null;

                    if (shippedLot.getShipDate() != null)
                    {
                        shipDate = shippedLot.getShipDate();
                    }
                    if (jsiShipStatus.getShipDate() != null && jsiShipStatus.getShipDate().trim().length() > 0)
                    {
                        shippedDate = jsiShipStatus.getShipDate();
                    }
                    if ((shippedDate != null) && (shipDate != null))
                    {
                        java.util.Date tempDate1 = StringUtils.getSQLDate(shippedDate, "MM/dd/yyyy");
                        java.util.Date tempDate2 = StringUtils.getSQLDate(shipDate, "MM/dd/yyyy");
                        if (tempDate1 != null && tempDate2 != null)
                        {
                            if (tempDate1.compareTo(tempDate2) > 0)
                            {
                                shippedDate = shipDate;
                            }
                        }
                    }

                    String salesOrderNo = null;
                    if (jsiShipStatus.getSalesOrderNo() != null && "-".equalsIgnoreCase(jsiShipStatus.getSalesOrderNo()))
                    {
                        salesOrderNo = null;
                    }
                    else
                    {
                        salesOrderNo = jsiShipStatus.getSalesOrderNo();
                    }

                    String hawb = null;
                    if (jsiShipStatus.getHawb() != null && "-".equalsIgnoreCase(jsiShipStatus.getHawb()))
                    {
                        hawb = null;
                    }
                    else
                    {
                        hawb = jsiShipStatus.getHawb();
                    }

                    String mawb = null;
                    if (jsiShipStatus.getMawb() != null && "-".equalsIgnoreCase(jsiShipStatus.getMawb()))
                    {
                        mawb = null;
                    }
                    else
                    {
                        mawb = jsiShipStatus.getMawb();
                    }

                    shippedLot.setPartNumber(partNumber);
                    shippedLot.setLotNumber(lotNumber);
                    shippedLot.setFabLotNumber(lotNumber);
                    shippedLot.setShipDate(shippedDate);
                    shippedLot.setShipQty(shipQty + "");
                    shippedLot.setCurrentLocation(LOCATION_TYPE_FINISHED_GOODS);
                    shippedLot.setCustomerPO(jsiShipStatus.getPoNumber());
                    shippedLot.setVendorName(VENDOR_NAME_JSI);
                    shippedLot.setMawb(mawb);
                    shippedLot.setHawb(hawb);
                    shippedLot.setInvoiceNumber(jsiShipStatus.getJobNumber());
                    shippedLot.setCustomerSO(salesOrderNo);
                    shippedLot.setNextLocation(jsiShipStatus.getShipTo());
                }
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
            log("ERROR!ERROR! While parsing the JSI Ship Details" + e);
            System.out.println("ERROR!ERROR! While parsing the JSI Ship Details" + e);
        }
    }

    /**
     *
     */
    private void printVersionInfo()
    {
        String info = "\n\n+----------- Running JSI FG Data Parser on " + new java.util.Date(System.currentTimeMillis()) + " -------------+\n" +
                "\n+---------------------------------------------------------------+\n" +
                "+                                                                \n" +
                "+           JSI FG Data Interpreter - Beta          \n" +
                "+                                                                \n" +
                "+    Copy Right (C) 2007 - ScalarSoft Inc., All rights reserved.  \n" +
                "+                                                                \n" +
                "+---------------------------------------------------------------+\n";
        System.out.println(info);
        log(info);
    } //end of printVersionInfo

    /**
     *
     * @param message
     */
    private void log(String message)
    {

        if (message == null) return;

        if (m_parserLogger != null)
        {
            synchronized (m_parserLogger)
            {
                m_parserLogger.logDebug(message + LINE_SEPARATOR);
            }
        }
        else
        {
            System.out.println(message);
        }
    }
}
